import { decode } from 'js-base64';
import { data, stepData } from './data';

interface IQuestionInfo {
  question: string;
  rightAns: string;
  ans: string[];
}

interface IStepQuestionInfo {
  question: string;
  ans: string[];
}

// 产生随机数组
function generateRandomIndex(count: number) {
  const array: number[] = [];

  for (let i = 0; i < count; i++) {
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const rand = parseInt((Math.random() * count).toString());
      if (!array.includes(rand)) {
        array.push(rand);
        break;
      }
    }
  }

  return array;
}

/**
 * 生成打乱的题目(选项也打乱)
 * 同时返回题目的数目
 */
export function createRandomQuestion() {
  const temp: IQuestionInfo[] = [];
  const array: number[] = generateRandomIndex(data.length);

  for (let i = 0; i < data.length; i++) {
    temp.push(JSON.parse(JSON.stringify(data[array[i]]))); //深拷贝
    temp[i].ans.sort(() => {
      //打乱选项
      return 0.5 - Math.random();
    });
    temp[i].question = decode(temp[i].question);
    temp[i].rightAns = decode(temp[i].rightAns);
    for (let j = 0; j < 4; j++) {
      temp[i].ans[j] = decode(temp[i].ans[j]);
    }
  }

  return {
    num: data.length,
    question: temp,
  };
}

export function createStepQuestion() {
  const temp: IStepQuestionInfo[] = [];
  for (let i = 0; i < 8; i++) {
    temp.push(JSON.parse(JSON.stringify(stepData[i]))); //深拷贝
    temp[i].question = decode(temp[i].question);
    for (let j = 0; j < 3; j++) {
      temp[i].ans[j] = decode(temp[i].ans[j]);
    }
  }
  return (i: number) => {
    return temp[i];
  };
}
